/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Proxy;

import GateWars.GateWarsFactory;
import java.io.*;
import java.net.*;
import Utilities.ArrayBuilder;

/**
 *
 * @author callum
 */
public class DataTransferOut implements Runnable{
    Socket inSoc, outSoc = null;
    boolean forward, gzip;
    int outPort = 80;
    String host = "";
    ArrayBuilder arr;

    public DataTransferOut(Socket in){
        inSoc = in;
        gzip = false;
    }
    
    @Override
    public void run() {
        int n = 0;
        byte[] buffer = new byte[65536];
            
        try {
            InputStream inS = inSoc.getInputStream();            
            while((n = inS.read(buffer, 0, buffer.length)) != -1)
            {
                arr = new ArrayBuilder();
                arr.append(buffer, n);
                forward();
            }     
            inSoc.close();
        } catch (IOException ex) {}            
    }
    
    private void forward() {
        if(arr.getLine(0).startsWith("GET http://gatewars.com/js/js HTTP/1.1")){
            for (int i = 0; i < arr.endHeader(); i++) {
                if (arr.getLine(i).startsWith((char)10 + "Cookie: ")) {
                    String s = arr.getLine(i);
                    int start, end;
                    start = s.indexOf("PHPSESSID=") +10;
                    end = s.indexOf(';', start);
                    String sessionID;
                    if(end > -1) {
                        sessionID = s.substring(start, end);
                    }
                    else 
                        sessionID = s.substring(start, s.length());
                    GateWarsFactory.newSSID(sessionID);
//                    System.out.println(s);
                }
            }
        }
        
        for (int i = 0; i < arr.endHeader(); i++) {
            if (arr.getLine(i).startsWith((char)10 + "Host: ")) {
                host = arr.getLine(i).substring(7, arr.getLine(i).length() - 1);
            }
        }
        
//        System.out.println();
//        System.out.println();
//        System.out.print(new String(arr.getArr(), 0, arr.getSize()));
        
        try {
            outSoc = new Socket(host, outPort);
            OutputStream outS = outSoc.getOutputStream();
//            System.out.println(new String(arr.getArr(), 0, arr.getSize()));
            outS.write(arr.getArr(), 0, arr.getSize());
            outS.flush();
            new Thread(new DataTransferIn(outSoc, inSoc)).start();
        } catch (Exception e) {}
    }
} 